import { createRouter, createWebHistory } from 'vue-router'
import { useCandidateStore, useEnterpriseStore } from '@/stores'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 异步写法
    // 登录
    {
      path: '/',
      component: () => import('@/views/layout/loginLayout.vue'),
      redirect: '/login/candidate',
      children: [
        {
          path: '/login/candidate',
          component: () => import('@/views/login/candidateLogin.vue')
        },
        {
          path: '/login/enterprise',
          component: () => import('@/views/login/enterpriseLogin.vue')
        }
      ]
    },
    // 个人
    {
      path: '/candidate',
      component: () => import('@/views/layout/candidateLayout.vue'),
      redirect: '/candidate/uploads',
      meta: { requiresCandidateAuth: true }, // 标记需要candidate登录权限
      children: [
        {
          path: '/candidate/uploads',
          component: () => import('@/views/candidate/candidateUploads.vue')
        },
        {
          path: '/candidate/manage',
          component: () => import('@/views/candidate/candidateManage.vue')
        },
        {
          path: '/candidate/profile',
          component: () => import('@/views/candidate/candidateProfile.vue')
        },
        {
          path: '/candidate/password',
          component: () => import('@/views/candidate/candidatePassword.vue')
        }
      ]
    },
    // 企业
    {
      path: '/enterprise',
      component: () => import('@/views/layout/enterpriseLayout.vue'),
      redirect: '/enterprise/manage',
      meta: { requiresEnterpriseAuth: true }, // 标记需要enterprise登录权限
      children: [
        {
          path: '/enterprise/manage',
          component: () => import('@/views/enterprise/enterpriseManage.vue')
        },
        {
          path: '/enterprise/assistant',
          component: () => import('@/views/enterprise/enterpriseAssistant.vue')
        },
        {
          path: '/enterprise/filepage',
          component: () => import('@/views/enterprise/fiePage.vue')
        }
      ]
    }
  ]
})
// 全局前置守卫
router.beforeEach((to) => {
  const enterpriseStore = useEnterpriseStore()
  const candidateStore = useCandidateStore()

  if (to.matched.some((record) => record.meta.requiresEnterpriseAuth)) {
    // enterprise登录权限
    if (!enterpriseStore.token) {
      // 如果token为空，重定向到enterprise登录页面
      return '/login/enterprise'
    }
  } else if (to.matched.some((record) => record.meta.requiresCandidateAuth)) {
    // candidate登录权限
    if (!candidateStore.token) {
      // 如果token为空，重定向到candidate登录页面
      return '/login/candidate'
    }
  }
})
export default router
